package com.caigou.service.impl;

import com.caigou.bean.cms.entity.Article;
import com.caigou.bean.cms.entity.ArticlePromoter;
import com.caigou.bean.cms.entity.ChannelData;
import com.caigou.bean.cms.param.ArticlePromoterQueryParam;
import com.caigou.bean.cms.param.ArticlePromoterParam;
import com.caigou.bean.vo.ArticlePromoterVO;
import com.caigou.component.*;
import com.caigou.mapper.cms.ArticleKeywordMapper;
import com.caigou.mapper.cms.ArticleMapper;
import com.caigou.mapper.cms.ArticlePromoterMapper;
import com.caigou.pojo.DictionaryOtherList;
import com.caigou.service.ArticlePromoterService;
import com.caigou.service.ChannelDataService;
import com.caigou.util.Result;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.IOException;
import java.io.InputStream;
import java.util.*;

@Slf4j
@Service("articlePromoterService")
public class ArticlePromoterServiceImpl implements ArticlePromoterService {

    @Resource
    private ArticlePromoterMapper articlePromoterMapper;

    @Resource
    private ArticleMapper articleMapper;

    @Resource
    private OSSComponent ossComponent;

    @Resource
    private SnowflakeComponent snowflakeComponent;// 雪花UUID组件

    @Resource
    private HtmlBuilderComponent htmlBuilderComponent;

    @Resource
    private ArticleKeywordMapper articleKeywordMapper;

    @Resource
    private ChannelDataService channelDataService;

    @Resource
    private HtmlDetailBuilderComponent htmlDetailBuilderComponent;

    @Resource
    private RabbitProducer rabbitProducer;

    @Override
    public List<DictionaryOtherList> loadArticlePromoterList() {
        return articlePromoterMapper.loadArticlePromoterList();
    }

    public ArticlePromoter selectByPrimaryKey(Integer id){
        return articlePromoterMapper.selectByPrimaryKey(id);
    }

    public PageInfo<ArticlePromoter> queryArticlePromoter(ArticlePromoterQueryParam articlePromoterQueryParam) {
        Page<?> page = PageHelper.startPage(articlePromoterQueryParam.getPageNum(), articlePromoterQueryParam.getPageSize());
        List<ArticlePromoter> articlePromoterList = articlePromoterMapper.queryArticlePromoter(articlePromoterQueryParam);
        PageInfo<ArticlePromoter> articlePromoterPageInfo = new PageInfo<>(articlePromoterList);
        return articlePromoterPageInfo;
    }

    public List<ArticlePromoter> queryArticlePromoterAll(ArticlePromoterQueryParam articlePromoterQueryParam){
        List<ArticlePromoter> articlePromoterList = articlePromoterMapper.queryArticlePromoter(articlePromoterQueryParam);
        return articlePromoterList;
    }

    /**
     * 增加稿件作者
     * @param file
     * @param name
     * @param authorPost
     * @param authorIntro
     * @param contractInfo
     * @param notes
     * @param userId
     * @return
     */
    public Result saveOrUpdateArticlePromoter(MultipartFile file, Integer id, String name, String authorPost, String authorIntro,
                                              String contractInfo, String notes, String userId){
        ArticlePromoter articlePromoter = null;
        String oldAuthorImage = null;
        if(id!=null){//更新推荐作者
            articlePromoter = selectByPrimaryKey(id);
            if(articlePromoter==null){
                return Result.error("修改作者信息失败，没有这个作者");
            }
        }
        log.info("saveOrUpdateArticlePromoter file={}, id={}", file, id);
        //处理上传作者图片
        try{
            String fileUrl = null;
            //上传图片
            if(file!=null){
                log.info("--------file is not null--------");;
                String fileName = file.getOriginalFilename();
                String fileExtension = "";
                int idx = fileName.lastIndexOf(".");
                if(idx>0){
                    fileExtension = fileName.substring(idx);
                    //String imageFileFormat = fileExtension.substring(1);
                }else{
                    log.error("上传文件错误，没有扩展名, fileName={}", fileName);
                    return Result.custom(400, "上传图片没有扩展名", "上传图片没有扩展名");
                }
                if(!fileExtension.equalsIgnoreCase(".png")&&!fileExtension.equalsIgnoreCase(".jpg")&&!fileExtension.equalsIgnoreCase(".gif")){
                    return Result.custom(400, "上传图片格式错误", "上传图片格式错误");
                }
                //文件重命名
                long snowflakeId = snowflakeComponent.getInstance().nextId();
                String newFileName = snowflakeId+fileExtension;
                InputStream originInputStream = file.getInputStream();
                String articlePromoterFolder = "author/";
                fileUrl = ossComponent.uploadToOSS(originInputStream, fileName, newFileName, articlePromoterFolder);
                log.info("upload author's image to oss, fileUrl={}", fileUrl);
            }
            Date currentTime = new Date(System.currentTimeMillis());
            if(articlePromoter==null){//新增
                articlePromoter = new ArticlePromoter();
                articlePromoter.setCreateTime(currentTime);
                articlePromoter.setIsForbid(0);
            }
            //新增、更新均设置以下信息
            articlePromoter.setName(name);
            articlePromoter.setAuthorPost(authorPost);
            articlePromoter.setAuthorIntro(authorIntro);
            articlePromoter.setContractInfo(contractInfo);
            articlePromoter.setNotes(notes);
            articlePromoter.setUpdateTime(currentTime);
            log.info("before saveOrUpdateArticlePromoter fileUrl={}", fileUrl);
            if(fileUrl!=null) {
                articlePromoter.setAuthorImage(fileUrl);
            }
            if(id==null){//新增
                int count = articlePromoterMapper.insertSelective(articlePromoter);
                if(count>0){
                    //生成推荐作者html碎片
                    htmlBuilderComponent.buildPromoterHtml(articlePromoter);
                    return Result.success(articlePromoter);
                    //return Result.success("增加作者成功");
                }else{
                    return Result.error("增加作者失败");
                }
            }else{//更新
                int count = articlePromoterMapper.updateArticlePromoter(articlePromoter);
                if(count>0){
//                    //删除原有作者头像
//                    log.info("删除原有作者头像,原有的头像url={}", oldAuthorImage);
//                    ossComponent.deleteFromOSS(oldAuthorImage);

                    //生成推荐作者html碎片
                    htmlBuilderComponent.buildPromoterHtml(articlePromoter);

                    //重新生成作者的所有文章详情页面
                    //this.updateArticleDetailHtmlByPromoterId(articlePromoter.getId());
                    Map<String, Object> msgMap = new HashMap();
                    msgMap.put("promoterId", articlePromoter.getId());
                    msgMap.put("operation", "updateArticleAuthor");
                    rabbitProducer.sendArticleAuthorMessage(msgMap);

                    return Result.success("更新作者成功");
                }else{
                    return Result.error("更新作者失败");
                }
            }

        }catch(IOException e){
            log.error(e.getMessage(), e);
            return Result.error("增加/更新作者失败");
        }
    }

    public void updateArticleDetailHtmlByPromoterId(Integer promoterId){
        List<Article> articleList = articleMapper.listArticleByArticleAuthor(promoterId);
        for(Article article:articleList){
            //重新生成该作者相关文章详情页
            ChannelData channelData = channelDataService.loadLastChannelData(article.getArticleId());
            String url = null;
            if (null == channelData) {
                url = htmlDetailBuilderComponent.buildArticleHtml(article.getArticleId(), "999");
            } else {
                url = htmlDetailBuilderComponent.buildArticleHtml(article.getArticleId(), channelData.getPlateId());
            }
            log.info("重新生成该作者的文章页，作者id={}, url={}", promoterId, url);
        }
    }

    /**
     * 获取推荐作者详情
     * @param articlePromoterParam
     * @return
     */
    public  Result getArticlePromoter(ArticlePromoterParam articlePromoterParam){
        Integer articlePromoterId = articlePromoterParam.getArticlePromoterId();
        ArticlePromoter articlePromoter = articlePromoterMapper.selectByPrimaryKey(articlePromoterId);
        if(articlePromoter!=null){
            return Result.success(articlePromoter);
        }else{
            return Result.custom(400, "参数有误", "没有该作者信息");
        }
    }

    /**
     * 获取推荐作者详细详细，包括发布的文章数量，最新文章列表等
     * @param articlePromoterId
     * @return
     */
    public Result getArticlePromoterByArticlePromoterId(Integer articlePromoterId){
        ArticlePromoter articlePromoter = articlePromoterMapper.selectByPrimaryKey(articlePromoterId);
        if(articlePromoter!=null){
            int count = articleMapper.getArticleCountByArticlePromoter(articlePromoterId);
            List<Article> latestArticles = articleMapper.listLatestArticleByArticlePromoter(articlePromoterId);
            ArticlePromoterVO articlePromoterVO = new ArticlePromoterVO();
            articlePromoterVO.setArticleCount(count);
            articlePromoterVO.setLatestArticles(latestArticles);
            articlePromoterVO.setId(articlePromoterId);
            articlePromoterVO.setName(articlePromoter.getName());
            articlePromoterVO.setAuthorPost(articlePromoter.getAuthorPost());
            articlePromoterVO.setAuthorIntro(articlePromoter.getAuthorIntro());
            articlePromoterVO.setAuthorImage(articlePromoter.getAuthorImage());
            articlePromoterVO.setContractInfo(articlePromoter.getContractInfo());
            articlePromoterVO.setNotes(articlePromoter.getNotes());
            articlePromoterVO.setIsForbid(articlePromoter.getIsForbid());
            return Result.success(articlePromoterVO);
        }else{
            return Result.custom(400, "参数有误", "没有该作者信息");
        }
    }


    /**
     * 更新作者禁用状态
     * @param articlePromoterParam
     * @return
     */
    public Result updateArticlePromoterIsForbid(ArticlePromoterParam articlePromoterParam){
        articlePromoterParam.setUpdateTime(new Date(System.currentTimeMillis()));
        int count = articlePromoterMapper.updateArticlePromoterIsForbid(articlePromoterParam);
        if(count>0){
            return Result.success("更新作者禁用状态成功");
        }else{
            return Result.custom(400, "更新作者禁用状态失败", "更新作者禁用状态失败");
        }
    }

    @Override
    public List<String> loadPromoterIdByName(String author) {
        return articlePromoterMapper.loadPromoterIdByName(author);
    }

}
